// 'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i
function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || '图图云平台' // page title
const IS_PRODUCTION = process.env.NODE_ENV === 'production'

const cdn = {
  css: [
    'https://unpkg.com/element-ui@2.13.2/lib/theme-chalk/index.css'
  ],
  js: [
    'https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.min.js',
    'https://cdn.bootcdn.net/ajax/libs/vue-router/3.0.2/vue-router.min.js',
    'https://cdn.bootcdn.net/ajax/libs/vuex/3.1.0/vuex.min.js',
    'https://cdn.bootcdn.net/ajax/libs/axios/0.18.1/axios.min.js',
    'https://unpkg.com/element-ui@2.13.2/lib/index.js',
    'https://cdn.bootcdn.net/ajax/libs/echarts/5.0.1/echarts.min.js'
  ]
}
const timestamp = new Date().getTime()
module.exports = {
  // 部署生产环境和开发环境下的URL。
  // 默认情况下，Vue CLI 会假设你的应用是被部署在一个域名的根路径上
  // 例如 https://www.guoyiit.com/。如果应用被部署在一个子路径上，你就需要用这个选项指定这个子路径。例如，如果你的应用被部署在 https://www.guoyiit.com/admin/，则设置 baseUrl 为 /admin/。
  publicPath: '/',
  // 在npm run build 或 yarn build 时 ，生成文件的目录名称（要和baseUrl的生产环境路径一致）（默认dist）
  outputDir: 'dist',
  // 用于放置生成的静态资源 (js、css、img、fonts) 的；（项目打包之后，静态资源会放在这个文件夹下）
  assetsDir: 'static',
  // 是否开启eslint保存检测，有效值：ture | false | 'error'
  // lintOnSave: process.env.NODE_ENV === 'development',
  lintOnSave: false,
  // 如果你不需要生产环境的 source map，可以将其设置为 false 以加速生产环境构建。
  productionSourceMap: false,
  // webpack-dev-server 相关配置
  devServer: {
    disableHostCheck: true,
    port: 8000,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
  },
  configureWebpack: {
    output: {
      // 修改输出js目录名及文件名
      filename: `js/[name]-test-${timestamp}.js`,
      chunkFilename: `js/[name]-test-${timestamp}.js`,
    },
  },
  // configureWebpack: config => {

  //   // 需要 npm i -D compression-webpack-plugin
  //   const plugins = [];
  //   plugins.push(new CompressionWebpackPlugin({
  //     filename: `[path][base]${timestamp}.gz`,  //压缩后的文件策略
  //     algorithm: "gzip",             //压缩方式
  //     test: productionGzipExtensions,//可设置需要压缩的文件类型
  //     //     include:'', //符合任何这些条件的文件
  //     //     exclude:'',//排除压缩的文件
  //     threshold: 1024, //大于10240字节的文件启用压缩
  //     minRatio: 0.8, // 压缩比率大于等于0.8时不进行压缩
  //     deleteOriginalAssets: false,//是否删除压缩前的文件，默认false
  //   }));

  //   config.plugins = [...config.plugins, ...plugins];
  //   return {
  //     //浏览器标题
  //     name: name
  //   }
  // },
  chainWebpack(config) {

    if (IS_PRODUCTION) {
      config.plugin('html').tap(args => {
        args[0].cdn = cdn
        return args
      })

    }
    //  // 查看打包文件体积大小
    //  config
    //  .plugin('webpack-bundle-analyzer')
    //  .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)

    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch')

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single')
        }
      )
  }
}
